<template>
  <el-dialog :modelValue="modelValue" title="权限调整" width="80%" align-center class="public-dialog" @close="handleClose" draggable destroy-on-close>
    <div class="content" v-loading="loading">
      <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="分配权限" name="user"></el-tab-pane>
        <el-tab-pane label="禁用权限" name="user_disable"></el-tab-pane>
      </el-tabs>
      <div class="name">
        <span>英文名: {{ userInfo?.en_name || "-" }}</span>
        <span>真实姓名: {{ userInfo?.realname || "-" }}</span>
      </div>
      <div v-show="activeName == 'user'">
        <div class="role">
          <el-tag class="mx-1" type="info" effect="plain" size="large" :round="true" v-for="(item, index) in authorityData?.roles || []" :key="index">{{ item.role_name }}</el-tag>
        </div>
        <div class="radio">
          <el-radio-group v-model="radioType" @change="handleradioType">
            <el-radio v-for="item in radioTypeData" :key="item.value" :label="item.value" size="large">{{ item.label }}</el-radio>
          </el-radio-group>
          <el-link type="primary" :underline="false" @click="clearCustomize">清除账户自定义权限</el-link>
        </div>
        <el-tabs type="border-card" class="tab-pane">
          <el-tab-pane label="菜单权限">
            <el-cascader-panel :key="1" v-model="allAuth[radioType].menu_ids" ref="dataMenu" :options="optionsData.menu_options" :props="cascaderProps.cascaderProps" class="cascaderPanel" />
          </el-tab-pane>
          <el-tab-pane label="按钮授权">
            <el-cascader-panel :key="2" v-model="allAuth[radioType].button_ids" ref="dataButton" :options="optionsData.button_options" :props="cascaderProps.cascaderProps" class="cascaderPanel" />
          </el-tab-pane>
          <el-tab-pane label="数据权限">
            <el-cascader-panel :key="3" ref="dataUser" v-model="allAuth[radioType].data_user_ids" :options="optionsData.data_options" :props="cascaderProps.useCascaderProps" class="cascaderPanel" />
          </el-tab-pane>
          <el-tab-pane label="属性权限">
            <div class="attribute">
              <div>
                <div class="text">商品权限</div>
                <el-tree
                  :key="4"
                  :props="cascaderProps.goodsProps"
                  :data="optionsData.goods_category_options"
                  show-checkbox
                  :default-checked-keys="allAuth[radioType].goods_category_ids"
                  ref="dataGoods"
                  node-key="id"
                />
              </div>
              <div class="ml-[8px] mr-[8px]">
                <div class="text">仓库权限</div>
                <el-tree
                  :key="5"
                  :props="cascaderProps.warehouseProps"
                  :data="optionsData.warehouse_options"
                  show-checkbox
                  :default-checked-keys="allAuth[radioType].warehouse_ids"
                  node-key="warehouse_id"
                  ref="dataWarehouse"
                />
              </div>
              <div>
                <div class="text">字段权限</div>
                <el-tree
                  :key="6"
                  :props="cascaderProps.menuProps"
                  :data="optionsData.field_attr_options"
                  show-checkbox
                  :default-checked-keys="allAuth[radioType].field_attr_ids"
                  ref="dataField"
                  node-key="id"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div v-show="activeName == 'user_disable'">
        <el-tabs type="border-card" class="tab-pane">
          <el-tab-pane label="菜单权限">
            <el-cascader-panel
              :key="9"
              v-model="userDisable.menu_ids"
              ref="dataMenuDisable"
              :options="optionsData.menu_options"
              :props="{ ...cascaderProps.cascaderProps, emitPath: false }"
              class="cascaderPanel"
            />
          </el-tab-pane>
          <el-tab-pane label="按钮授权">
            <el-cascader-panel
              :key="8"
              v-model="userDisable.button_ids"
              ref="dataButtonDisable"
              :options="optionsData.button_options"
              :props="{ ...cascaderProps.cascaderProps, emitPath: false }"
              class="cascaderPanel"
            />
          </el-tab-pane>
          <el-tab-pane label="数据权限">
            <el-cascader-panel
              :key="7"
              ref="dataUserDisable"
              v-model="userDisable.data_user_ids"
              :options="optionsData.data_options"
              :props="{ ...cascaderProps.useCascaderProps, emitPath: false }"
              class="cascaderPanel"
            />
          </el-tab-pane>
          <el-tab-pane label="属性权限">
            <div class="attribute">
              <div>
                <div class="text">商品权限</div>
                <el-tree
                  :key="4"
                  :props="cascaderProps.goodsProps"
                  :data="optionsData.goods_category_options"
                  show-checkbox
                  :default-checked-keys="userDisable.goods_category_ids"
                  ref="dataGoodsDisable"
                  node-key="id"
                />
              </div>
              <div class="ml-[8px] mr-[8px]">
                <div class="text">仓库权限</div>
                <el-tree
                  :key="5"
                  :props="cascaderProps.warehouseProps"
                  :data="optionsData.warehouse_options"
                  show-checkbox
                  :default-checked-keys="userDisable.warehouse_ids"
                  node-key="warehouse_id"
                  ref="dataWarehouseDisable"
                />
              </div>
              <div>
                <div class="text">字段权限</div>
                <el-tree
                  :key="6"
                  :props="cascaderProps.menuProps"
                  :data="optionsData.field_attr_options"
                  show-checkbox
                  :default-checked-keys="userDisable.field_attr_ids"
                  ref="dataFieldDisable"
                  node-key="id"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="ml-[15px] text-[red]">提示 : 只能修改账号自定义权限,不能调整账号角色的权限</div>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button @click="handleClose(true)">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="loading"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="VRole">
import { ElMessage } from "element-plus"
import { radioTypeData, cascaderProps, transformData, oneArray, recursivelyAddDisabled } from "./data"
import { organizationList } from "@/api/system/role"
import { getMenus } from "@/api/menu"
import api from "../../api"
import { flattenAndRemoveDuplicates } from "@/utils/tools.js"
// 声明接收参数
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  id: { type: [String, Number], default: "" },
})
const emit = defineEmits(["update:modelValue", "refresh", "close"])
const loading = ref(false)
const radioType = ref("all")
const authorityData = ref({})
const userInfo = ref({})
const dataGoods = ref([])
const dataWarehouse = ref([])
const dataField = ref([])
const allAuth = ref({
  all: {
    button_ids: [],
    data_user_ids: [],
    field_attr_ids: [],
    goods_category_ids: [],
    menu_ids: [],
    warehouse_ids: [],
  },
  role_owner: {
    button_ids: [],
    data_user_ids: [],
    field_attr_ids: [],
    goods_category_ids: [],
    menu_ids: [],
    warehouse_ids: [],
  },
  user_owner: {
    button_ids: [],
    data_user_ids: [],
    field_attr_ids: [],
    goods_category_ids: [],
    menu_ids: [],
    warehouse_ids: [],
  },
})

const optionsData = ref({})
const getBaseData = async () => {
  try {
    let res1 = await api.baseData({ get: ["access"] })
    let warehouseData = transformData(res1?.data?.access?.warehouse_options || [])
    optionsData.value = res1.data.access
    optionsData.value.warehouse_options = warehouseData
    let res2 = await organizationList()
    optionsData.value.data_options = res2.data
  } catch (error) {}
}
const userDisable = ref({
  button_ids: [],
  data_user_ids: [],
  field_attr_ids: [],
  goods_category_ids: [],
  menu_ids: [],
  warehouse_ids: [],
})
const activeName = ref("user")
const dataGoodsDisable = ref()
const dataWarehouseDisable = ref()
const dataFieldDisable = ref()

const handleClick = (e) => {
  //
}
watch(
  () => props.id,
  (val) => {
    if (val) {
      getBaseData()
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)
//详情
const getDetail = async (id) => {
  try {
    const { data } = await api.getAccess({ id })
    allAuth.value = data?.perm
    userInfo.value = data?.userinfo
    userDisable.value = data?.user_disable_perm
    authorityData.value = JSON.parse(JSON.stringify(data))
  } catch (error) {}
}

//单选

const handleradioType = async (val) => {
  let data = JSON.parse(JSON.stringify(authorityData.value))
  await nextTick()
  allAuth.value = data.perm
}

//清除账户自定义权限
const clearCustomize = () => {
  let data = JSON.parse(JSON.stringify(allAuth.value))
  switch (radioType.value) {
    case "user_owner":
      for (let key in allAuth.value.user_owner) {
        allAuth.value.user_owner[key] = []
      }
      break
    case "all":
      for (let key in allAuth.value.all) {
        allAuth.value.all[key] = data.role_owner[key]
      }
      break
  }
}
const dataUser = ref()
const handleSave = async () => {
  try {
    let data = JSON.parse(JSON.stringify(authorityData.value))
    for (let key in allAuth.value) {
      for (let k in allAuth.value[key]) {
        allAuth.value[key][k] = flattenAndRemoveDuplicates(allAuth.value[key][k])
      }
    }
    const { roles, userinfo } = data
    allAuth.value[radioType.value].goods_category_ids = dataGoods.value?.getCheckedNodes()?.map((item) => item.id)
    allAuth.value[radioType.value].warehouse_ids = dataWarehouse.value?.getCheckedNodes()?.map((item) => item.warehouse_id)
    allAuth.value[radioType.value].field_attr_ids = dataField.value
      ?.getCheckedNodes()
      ?.filter((item) => item.field_type == 3)
      ?.map((it) => it.id)
    let dataAllUser = dataUser.value
      ?.getCheckedNodes()
      .filter((item) => item.data.organization_type == 2)
      .map((it) => {
        return it.value
      })
    switch (radioType.value) {
      case "role_owner":
        allAuth.value = data.perm
        break
      case "user_owner":
        //拿到自定义的权限和角色权限做补集
        allAuth.value.user_owner.data_user_ids = dataAllUser
        for (let key in allAuth.value.user_owner) {
          allAuth.value.user_owner[key] = allAuth.value.user_owner[key].filter((item) => !allAuth.value.role_owner[key]?.includes(item))
        }
        break
      case "all":
        allAuth.value.all.data_user_ids = dataAllUser
        for (let key in allAuth.value.all) {
          allAuth.value.user_owner[key] = allAuth.value.all[key].filter((item) => !allAuth.value.role_owner[key]?.includes(item))
        }
        break
    }
    // menu_ids
    // console.log(6666)
    // console.log({ roles, userinfo, id: props.id, perm: allAuth.value })
    // console.log(userDisable.value)

    let user_disable_perm = {
      button_ids: userDisable.value.button_ids,
      data_user_ids: userDisable.value.data_user_ids,
      menu_ids: userDisable.value.menu_ids,
    }
    user_disable_perm.goods_category_ids = dataGoodsDisable.value?.getCheckedNodes()?.map((item) => item.id)
    user_disable_perm.warehouse_ids = dataWarehouseDisable.value?.getCheckedNodes()?.map((item) => item.warehouse_id)
    user_disable_perm.field_attr_ids = dataFieldDisable.value
      ?.getCheckedNodes()
      ?.filter((item) => item.field_type == 3)
      ?.map((it) => it.id)
    // console.log(user_disable_perm)
    // return
    loading.value = true
    const { code, message } = await api.setAccess({
      roles,
      userinfo,
      id: props.id,
      perm: allAuth.value,
      user_disable_perm,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success("保存成功!")
    handleClose(true)
  } catch (error) {
  } finally {
    loading.value = false
  }
}

const handleClose = async (refresh) => {
  authorityData.value = {}
  radioType.value = "all"
  optionsData.value = {}
  userInfo.value = {}
  emit("update:modelValue", false)
  emit("close")
  if (refresh) emit("refresh")
}
</script>
<style lang="scss" scoped>
.attribute {
  display: flex;
  height: 400px;
  overflow: auto;
  & > div {
    flex: 1;
    height: 100%;
    overflow: auto;
    border: 1px solid #e6e7e9;
    .text {
      text-align: center;
      line-height: 40px;
      background-color: #f6faff;
      color: #3487ff;
    }
  }
}
.content {
  align-items: center;
  .name {
    margin: 8px;
    span {
      margin-right: 20px;
    }
  }
  .role {
    margin: 0 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f7f9fe;
  }
  .radio {
    display: flex;
    margin: 0 15px;
    justify-content: space-between;
  }
  span {
    margin-left: 5px;
  }
}
.dialogName {
  font-size: 16px;
  font-weight: bold;
}
.input-switch {
  width: calc(100% - 58px);
  margin-right: 10px;
}
:deep(.tab-pane) {
  border-radius: 10px;
  .el-tabs__content {
    padding: 8px;
  }
  .el-tabs__header {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
  }
  .el-tabs__nav {
    width: 100%;
    border-radius: 10px;
    display: flex;
  }
  .el-tabs__item.is-active {
    color: #fff !important;
    background-color: #3487ff !important;
  }
  .el-tabs__item {
    flex: 1;
    color: var(--base-tabs-color) !important;
    text-align: center;
    background: var(--base-color) !important;
    border: 1px solid var(--base-border-color) !important;
    &:hover {
      color: #fff !important;
      background-color: #3487ff !important;
    }
  }
  .el-tabs__item:not(.is-disabled):hover {
    color: #fff;
  }
  .el-tabs__item:first-child {
    border-top-left-radius: 10px;
  }
  .el-tabs__item:last-child {
    text-align: center;
    border-top-right-radius: 10px;
  }
}
.cascaderPanel {
  overflow: auto;
  height: 400px;
  &:deep(.el-scrollbar__wrap) {
    height: 100% !important;
  }
}
:deep(.el-cascader-menu:last-child) {
  border-right: var(--el-cascader-menu-border);
}
:deep(.el-scrollbar__bar) {
  display: block !important;
}
</style>
